<?php

function AddVariable($Name, $Value, $Display = true, $Len = -1)
{
	/* assume session is started */
	$_SESSION['var'][$Name]['value'] = $Value;
	if(is_string($Value) && $Len == -1) $Len = strlen($Value);
	$_SESSION['var'][$Name]['len'] = $Len;
	$_SESSION['var'][$Name]['display'] = $Display;
}

function GetVariable($Name)
{
	return (isset($_SESSION['var'][$Name]['value'])?$_SESSION['var'][$Name]['value']:false);
}

function CheckAnswer($vars)
{
	foreach($vars as $v)
	{
		if(isset($_POST[$v]) == false) return false;
	}
	return true;
}

function ApplyModifier($modifier, $param, $replace, $var)
{
	$param[$replace] = $var;
	return call_user_func_array($modifier, $param);
}

function CheckAnswersEqual($vars, $modifier = null, $param = array(), $replace = 0)
{
	foreach($vars as $v)
	{
		if(isset($_POST[$v]) == false) return false;
		if($modifier != null)
		{
			$p = ApplyModifier($modifier, $param, $replace, $_POST[$v]);
			$v = ApplyModifier($modifier, $param, $replace, GetVariable($v));
			if($p != $v) return false;
		}
		else if($_POST[$v] != GetVariable($v)) return false;
	}
	return true;
}

function CheckAnswersEqualUnordered($vars, $modifier = null, $param = array(), $replace = 0)
{
	if(count($vars) != 2) return false;
	if(isset($_POST[$vars[0]]) == false || isset($_POST[$vars[1]]) == false) return false;
	if($_POST[$vars[0]] != GetVariable($vars[0]))
		if($_POST[$vars[0]] != GetVariable($vars[1]))
			return false;
	if($_POST[$vars[1]] != GetVariable($vars[1]))
		if($_POST[$vars[1]] != GetVariable($vars[0]))
			return false;
	return true;
}

function CheckAnswersAlmostEqual($vars, $precision)
{
	foreach($vars as $v)
	{
		if(isset($_POST[$v]) == false) return false;
		if(abs($_POST[$v] - GetVariable($v)) > $precision) return false;
	}
	return true;
}

function GetVarCount($t)
{
	$c = 0;
	if(!isset($t) || empty($t)) return 0;
	foreach($t as $val)
	{
		if($val['display'] == true) $c++;
	}
	return $c;
}

function DisplayVariables()
{
	$count = GetVarCount($_SESSION['var']);
	echo 'Nombre_variables=' . $count . '<br/>';
	if($count == 0) return;
	foreach($_SESSION['var'] as $name => $val)
	{
		if($val['display'] == false) continue;
		echo '[' . $name . ']<br/>';
		if($val['len'] != -1) echo 'Longueur=' . $val['len'] . '<br/>';
		echo 'Valeur=' . $val['value'] . '<br/>';
	}
}

?>